import 'dart:math';

import 'package:flutter/material.dart';

class CardView extends StatefulWidget {
  const CardView({super.key});

  @override
  CardViewState createState() => CardViewState();
}

class CardViewState extends State<CardView>
    with SingleTickerProviderStateMixin {
  double moveX = 0;
  double moveY = 0;

  AnimationController? _controller;
  Animation<double>? _animation;

  List<double> cardMoveX =
      List.generate(10, (index) => Random().nextInt(1000) - 500);

  @override
  void initState() {
    _controller = AnimationController(
      duration: const Duration(seconds: 4),
      vsync: this,
    );
    _animation = Tween<double>(begin: 0, end: 1).animate(_controller!)
      ..addListener(() {
        if (_animation!.isCompleted) {
          _controller?.reset();
        }
        setState(() {});
      });

    super.initState();
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return card1Widget();
  }

  Widget card1Widget() {
    return Container(
        color: Colors.blue,
        child: GestureDetector(
          onPanUpdate: (details) {
            debugPrint("dx:${details.delta.dy}");
            setState(() {
              moveX += details.delta.dx;
              moveY += details.delta.dy;
            });
          },
          //添加一个矩阵变换效果，当offsetX和offsetY变换时，图片呈现一个3D的视角变换效果
          child:SizedBox(
            width: double.infinity,
            height: double.infinity,
            child: Center(
              child: _card1Matrix(),
            ),
          ),
        )
      );
  }

  Widget _card1Matrix(){
    return Transform(
      transform: Matrix4(
        1, 0, 0, 0, //第1位x轴缩放，
        0, 1, 0, 0, //第2位y轴缩放，
        0, 0, 1, 0.002, //第4位透视深度参数
        0, 0, 0, 1, //前3位控制x,y,z方向的位移
      )
      // ..setEntry(3, 2, 0.002)
      ..rotateX(moveY / 100)
      ..rotateY(-moveX / 100)
      ,
      alignment: FractionalOffset.center,
      child: Container(
        width: 150,
        height: 150,
        decoration: BoxDecoration(
          border: Border.all(width: 3, color: Colors.transparent),
          borderRadius: BorderRadius.circular(10),
          image: const DecorationImage(
            image: AssetImage(
              'images/pic_scene_1.jpg',
            ),
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  Widget card2Widget() {
    double animationValue = 0;
    double cardOffsetY = 0;
    double cardRotationY = 0;
    if (_animation != null) {
      animationValue = _animation!.value;
      cardOffsetY = _calculateHeight(_animation!.value);
      cardRotationY = _animation!.value * 20;
    }
    debugPrint(cardOffsetY.toString());
    return Container(
        child: Center(
      child: GestureDetector(
        onTap: () {
          debugPrint("onTap");
          //随机生成每张卡片的x轴偏移量
          cardMoveX =
              List.generate(10, (index) => Random().nextInt(1000) - 500);
          _controller?.forward(from: 0);
        },
        //添加一个矩阵变换效果，当offsetX和offsetY变换时，图片呈现一个3D的视角变换效果
        child: Stack(
          children: List.generate(
              10,
              (index) => Transform(
                    transform: Matrix4.translationValues(
                        cardMoveX[index] * animationValue, cardOffsetY, 0)
                      ..setEntry(3, 2, 0.001)
                      ..rotateX(cardRotationY)
                      ..rotateY(cardMoveX[index] / 50 * animationValue),
                    alignment: FractionalOffset.center,
                    child: Container(
                      width: 50,
                      height: 50,
                      decoration: BoxDecoration(
                        border: Border.all(width: 3, color: Colors.transparent),
                        borderRadius: BorderRadius.circular(10),
                        image: DecorationImage(
                          image: AssetImage(
                            'images/pic_scene_${index % 3 + 1}.jpg',
                          ),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  )),
        ),
      ),
    ));
  }

  double _calculateHeight(double animationValue) {
    double time = animationValue * 4;
    //初速度
    double startV = -30;
    //重力加速度
    double _g = 9.8;
    //当前速度
    double v = startV + time * _g;
    //当前位置
    double currentY = v * time + 0.5 * _g * time * time;
    return currentY * 10;
  }
}
